<!-- src/pagesOrder/pages/detail/detail.vue -->
<script setup lang="ts">
import { useGuessList } from '@/composables/useGuessList.ts'
import { onMounted, ref, watch } from 'vue'
import XtxGuess from '@/components/XtxGuess.vue'
import {
  cancelOrderApi,
  confirmReceiptApi,
  delOrderApi,
  getOrderDetailApi,
  getOrderLogisticsApi,
  mockConsignmentApi,
  payMockApi,
} from '@/pagesOrder/api/order.ts'
import type { DetailLogistic, DetailOrderResult } from '@/types/order'
import DetailSkeleton from '@/pagesOrder/pages/detail/components/DetailSkeleton.vue'
import { OrderStatus, orderStatusMap } from '@/pagesOrder/api/constants.ts'
import debounce from 'lodash.debounce'
import { unFinished } from '@/utils/unFinished.ts'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getWindowInfo()
// 猜你喜欢
const { guessRef, onScrolltolower } = useGuessList()
// 弹出层组件
const popup = ref<UniHelper.UniPopupInstance>()
// 取消原因列表
const reasonList = ref([
  '商品无货',
  '不想要了',
  '商品信息填错了',
  '地址信息填写错误',
  '商品降价',
  '其它',
])
// 订单取消原因
const reason = ref('')
// 复制内容
const onCopy = (id: string) => {
  // 设置系统剪贴板的内容
  uni.setClipboardData({ data: id })
}
// 获取页面参数，订单id
const query = defineProps<{
  id: string
}>()

const pages = getCurrentPages()
// #ifdef MP-WEIXIN
const pageInstance = pages[pages.length - 1] as any
onMounted(() => {
  // 动画效果,导航栏背景色
  pageInstance.animate(
    '.navbar', // 选择器
    [{ backgroundColor: 'transparent' }, { backgroundColor: '#f8f8f8' }], // 关键帧信息
    1000, // 动画持续时长
    {
      scrollSource: '#scroller', // scroll-view 的选择器
      startScrollOffset: 0, // 开始滚动偏移量
      endScrollOffset: 50, // 停止滚动偏移量
      timeRange: 1000, // 时间长度
    },
  )
  // 动画效果,导航栏标题
  pageInstance.animate('.navbar .title', [{ color: 'transparent' }, { color: '#000' }], 1000, {
    scrollSource: '#scroller',
    timeRange: 1000,
    startScrollOffset: 0,
    endScrollOffset: 50,
  })
  // 动画效果,导航栏返回按钮
  pageInstance.animate('.navbar .back', [{ color: '#fff' }, { color: '#000' }], 1000, {
    scrollSource: '#scroller',
    timeRange: 1000,
    startScrollOffset: 0,
    endScrollOffset: 50,
  })
})
// #endif

const orderDetail = ref<DetailOrderResult>()
const getOrderDetail = async () => {
  const res = await getOrderDetailApi(query.id)
  orderDetail.value = res.result
}
getOrderDetail()

// 倒计时结束
const onTimeup = () => {
  if (orderDetail.value) orderDetail.value.orderState = OrderStatus.YiQuXiao
}

const isDev = import.meta.env.DEV
// 支付订单
const payOrder = debounce(async () => {
  // 开发环境：模拟支付，修改订单状态为已支付
  await payMockApi({ orderId: query.id })
  // // 生产环境：获取支付参数 + 发起微信支付
  // const res = await payOrderApi({ orderId: query.id })
  // await wx.requestPayment(res.result)
  // 关闭当前页，再跳转支付结果页
  uni.redirectTo({ url: `/pagesOrder/pages/payment/payment` })
}, 500)

// 模拟发货
const mockConsignment = async () => {
  if (isDev) {
    await mockConsignmentApi(query.id)
    uni.showToast({ icon: 'success', title: '模拟发货完成' })
    // 主动更新订单状态
    orderDetail.value!.orderState = OrderStatus.DaiShouHuo
  }
}

// 确认收货
const confirmReceipt = async () => {
  // 二次确认弹窗
  uni.showModal({
    content: '为保障您的权益，请收到货并确认无误后，再确认收货',
    success: async (success) => {
      if (success.confirm) {
        const res = await confirmReceiptApi(query.id)
        // 更新订单状态
        orderDetail.value = res.result
      }
    },
  })
}

const logisticList = ref<DetailLogistic[]>([])
// 组件初始化不用立即请求物流数据，因为初始化的时候 orderDetail.value 一定不存在
// 等 orderDetail.value 存在时，再请求物流数据
watch(
  // 依赖项：仅关注订单状态
  () => orderDetail.value?.orderState,

  // 状态变化处理函数，如果 newState 为 null 或 undefined（即无效状态），或者
  // newState 不在目标状态列表中（非待收货/待评价/已完成状态），则跳过物流数据请求。
  async (newState) => {
    // 状态有效性校验
    if (
      !newState ||
      ![OrderStatus.DaiShouHuo, OrderStatus.DaiPingJia, OrderStatus.YiWanCheng].includes(newState)
    ) {
      return
    }

    // 数据缓存校验（防止重复请求）
    if (logisticList.value.length) {
      return
    }

    // 数据请求过程
    const res = await getOrderLogisticsApi(query.id)
    logisticList.value = res.result.list
  },
)

// 删除订单
const delOrder = async () => {
  // 二次确认弹窗
  uni.showModal({
    content: '确定要删除该订单吗？',
    success: async (success) => {
      if (success.confirm) {
        await delOrderApi({ ids: [query.id] })
        uni.navigateBack()
      }
    },
  })
}

// 检查当前订单状态是否包含在目标状态列表中
const checkStatus = (targetStates: OrderStatus[]) => {
  if (!orderDetail.value) return false
  return targetStates.includes(orderDetail.value.orderState)
}

// 取消订单
const cancelOrder = debounce(async () => {
  if (!reason.value) return uni.showToast({ icon: 'none', title: '请选择取消原因' })

  // 发送请求
  const res = await cancelOrderApi(query.id, { cancelReason: reason.value })
  // 更新订单信息
  orderDetail.value = res.result
  // 关闭弹窗
  popup.value?.close!()
  // 轻提示
  uni.showToast({ icon: 'none', title: '订单取消成功' })
}, 500)
</script>

<template>
  <!-- 自定义导航栏: 默认透明不可见, scroll-view 滚动到 50 时展示 -->
  <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
    <view class="wrap">
      <navigator
        v-if="pages.length > 1"
        open-type="navigateBack"
        class="back icon-left"
        hover-class="none"
      ></navigator>
      <navigator
        v-else
        url="/pages/index/index"
        open-type="switchTab"
        class="back icon-home"
        hover-class="none"
      >
      </navigator>
      <view class="title">订单详情</view>
    </view>
  </view>
  <scroll-view scroll-y class="viewport" id="scroller" @scrolltolower="onScrolltolower">
    <view v-show="orderDetail">
      <!-- 订单状态 -->
      <view class="overview" :style="{ paddingTop: safeAreaInsets!.top + 20 + 'px' }">
        <!-- 待付款状态:展示去支付按钮和倒计时 -->
        <template v-if="orderDetail?.orderState === OrderStatus.DaiFuKuan">
          <view class="status icon-clock">等待付款</view>
          <view class="tips">
            <text class="money">应付金额: ¥ {{ orderDetail.payMoney.toFixed(2) }}</text>
            <text class="time">支付剩余</text>
            <uni-countdown
              :second="orderDetail.countdown"
              :show-colon="false"
              :show-day="false"
              color="#fff"
              splitor-color="#fff"
              @timeup="onTimeup"
            />
          </view>
          <view class="button" @tap="payOrder">去支付</view>
        </template>
        <!-- 其他订单状态:展示再次购买按钮 -->
        <template v-if="orderDetail && orderDetail.orderState !== OrderStatus.DaiFuKuan">
          <!-- 订单状态文字 -->
          <view class="status">{{ orderStatusMap[orderDetail.orderState].text }}</view>
          <view class="button-group">
            <navigator
              class="button"
              :url="`/pagesOrder/pages/create/create?orderId=${query.id}`"
              hover-class="none"
            >
              再次购买
            </navigator>
            <!-- 待发货状态：模拟发货,开发期间使用,用于修改订单状态为已发货 -->
            <view
              v-if="isDev && orderDetail.orderState === OrderStatus.DaiFaHuo"
              class="button"
              @tap="mockConsignment"
              >模拟发货
            </view>
            <view
              v-if="orderDetail.orderState === OrderStatus.DaiShouHuo"
              class="button"
              @tap="confirmReceipt"
              >确认收货
            </view>
          </view>
        </template>
      </view>
      <!-- 配送状态 -->
      <view class="shipment">
        <!-- 订单物流信息 -->
        <view v-for="item in logisticList" :key="item.id" class="item">
          <view class="message">
            {{ item.text }}
          </view>
          <view class="date">{{ item.time }}</view>
        </view>
        <!-- 用户收货地址 -->
        <view class="locate">
          <view class="user">
            {{ orderDetail?.receiverContact }} {{ orderDetail?.receiverMobile }}
          </view>
          <view class="address"> {{ orderDetail?.receiverAddress }}</view>
        </view>
      </view>

      <!-- 商品信息 -->
      <view class="goods">
        <view class="item">
          <navigator
            v-for="sku in orderDetail?.skus"
            :key="sku.id"
            :url="`/pages/goods/goods?id=${sku.spuId}`"
            hover-class="none"
          >
            <view class="navigator">
              <image class="cover" :src="sku.image" lazy-load></image>
              <view class="meta">
                <view class="name ellipsis">{{ sku.name }}</view>
                <view class="type">{{ sku.attrsText }}</view>
                <view class="price-quantity">
                  <view class="actual">
                    <text class="symbol">¥</text>
                    <text>{{ sku.curPrice.toFixed(2) }}</text>
                  </view>
                  <view class="quantity">x{{ sku.quantity }}</view>
                </view>
              </view>
            </view>
          </navigator>
        </view>
        <!-- 合计 -->
        <view class="total">
          <view class="row">
            <view class="text">商品总价:</view>
            <view class="symbol">{{ orderDetail?.totalMoney.toFixed(2) }}</view>
          </view>
          <view class="row">
            <view class="text">运费:</view>
            <view class="symbol">{{ orderDetail?.postFee.toFixed(2) }}</view>
          </view>
          <view class="row">
            <view class="text">应付金额:</view>
            <view class="symbol primary">{{ orderDetail?.payMoney.toFixed(2) }}</view>
          </view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="detail">
        <view class="title">订单信息</view>
        <view class="row">
          <view class="item">
            订单编号: {{ query.id }}
            <text class="copy" @tap="onCopy(query.id)">复制</text>
          </view>
          <view class="item">下单时间: {{ orderDetail?.createTime }}</view>
        </view>
      </view>

      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </view>
    <!-- 骨架屏组件 -->
    <DetailSkeleton v-if="!orderDetail" />
  </scroll-view>
  <!-- 底部操作栏 -->
  <view
    class="toolbar"
    v-if="orderDetail"
    :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
  >
    <!-- 待付款状态:展示支付按钮 -->
    <template v-if="orderDetail?.orderState === OrderStatus.DaiFuKuan">
      <view class="button primary" @tap="payOrder">去支付</view>
      <view class="button" @tap="popup?.open">取消订单</view>
    </template>
    <!-- 其他订单状态:按需展示按钮 -->
    <template v-else>
      <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
      <view
        class="button delete"
        v-if="checkStatus([OrderStatus.DaiPingJia, OrderStatus.YiWanCheng, OrderStatus.YiQuXiao])"
        @tap="delOrder"
      >
        删除订单
      </view>
      <!-- 待评价状态: 展示去评价 -->
      <view
        class="button"
        v-if="orderDetail?.orderState === OrderStatus.DaiPingJia"
        @tap="unFinished"
        >去评价
      </view>
      <!-- 待收货状态: 展示确认收货 -->
      <view
        class="button primary"
        v-if="orderDetail?.orderState === OrderStatus.DaiShouHuo"
        @tap="confirmReceipt"
        >确认收货
      </view>
      <navigator
        class="button secondary"
        :url="`/pagesOrder/pages/create/create?orderId=${query.id}`"
        hover-class="none"
      >
        再次购买
      </navigator>
    </template>
  </view>
  <!-- 取消订单弹窗 -->
  <uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="10rpx 10rpx 0 0">
    <view class="popup-root">
      <view class="title">订单取消</view>
      <view class="description">
        <view class="tips">请选择取消订单的原因：</view>
        <view class="cell" v-for="item in reasonList" :key="item" @tap="reason = item">
          <text class="text">{{ item }}</text>
          <text class="icon" :class="{ checked: item === reason }"></text>
        </view>
      </view>
      <view class="footer">
        <view class="button" @tap="popup?.close">取消</view>
        <view class="button primary" @tap="cancelOrder">确认</view>
      </view>
    </view>
  </uni-popup>
</template>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.navbar {
  width: 750rpx;
  color: #000;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9;
  /* background-color: #f8f8f8; */
  background-color: transparent;

  .wrap {
    position: relative;

    .title {
      height: 44px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
      /* color: #000; */
      color: transparent;
    }

    .back {
      position: absolute;
      left: 0;
      height: 44px;
      width: 44px;
      font-size: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      /* color: #000; */
      color: #fff;
    }
  }
}

.viewport {
  flex: 1;
  background-color: #f7f7f8;
}

.overview {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/order_bg.png);
  background-size: 750rpx auto;
  background-repeat: no-repeat;

  line-height: 1;
  padding-bottom: 30rpx;
  color: #fff;

  .status {
    font-size: 36rpx;
  }

  .status::before {
    margin-right: 6rpx;
    font-weight: 500;
  }

  .tips {
    margin: 30rpx 0;
    display: flex;
    font-size: 14px;
    align-items: center;

    .money {
      margin-right: 30rpx;
    }
  }

  .button-group {
    margin-top: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .button {
    width: 260rpx;
    height: 64rpx;
    margin: 0 10rpx;
    text-align: center;
    line-height: 64rpx;
    font-size: 28rpx;
    color: #27ba9b;
    border-radius: 68rpx;
    background-color: #fff;
  }
}

.shipment {
  line-height: 1.4;
  padding: 0 20rpx;
  margin: 20rpx 20rpx 0;
  border-radius: 10rpx;
  background-color: #fff;

  .locate,
  .item {
    min-height: 120rpx;
    padding: 30rpx 30rpx 25rpx 75rpx;
    background-size: 50rpx;
    background-repeat: no-repeat;
    background-position: 6rpx center;
  }

  .locate {
    background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/locate.png);

    .user {
      font-size: 26rpx;
      color: #444;
    }

    .address {
      font-size: 24rpx;
      color: #666;
    }
  }

  .item {
    background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/car.png);
    border-bottom: 1rpx solid #eee;
    position: relative;

    .message {
      font-size: 26rpx;
      color: #444;
    }

    .date {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.goods {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    padding: 30rpx 0;
    border-bottom: 1rpx solid #eee;

    .navigator {
      display: flex;
      margin: 20rpx 0;
    }

    .cover {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .price-quantity {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 6rpx;
      font-size: 24rpx;
      color: #444;

      .actual {
        margin-left: 10rpx;
      }

      .symbol {
        font-size: 20rpx;
      }
    }

    .original {
      color: #999;
      text-decoration: line-through;
    }

    .text {
      font-size: 22rpx;
    }
  }

  .total {
    line-height: 1;
    font-size: 26rpx;
    padding: 20rpx 0;
    color: #666;

    .row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10rpx 0;
    }

    .symbol::before {
      content: '¥';
      font-size: 80%;
      margin-right: 3rpx;
    }

    .primary {
      color: #cf4444;
      font-size: 36rpx;
    }
  }
}

.detail {
  line-height: 1;
  padding: 30rpx 20rpx 0;
  margin: 20rpx 20rpx 0;
  font-size: 26rpx;
  color: #666;
  border-radius: 10rpx;
  background-color: #fff;

  .title {
    font-size: 30rpx;
    color: #444;
  }

  .row {
    padding: 20rpx 0;

    .item {
      padding: 10rpx 0;
      display: flex;
      align-items: center;
    }

    .copy {
      border-radius: 20rpx;
      font-size: 20rpx;
      border: 1px solid #ccc;
      padding: 5rpx 10rpx;
      margin-left: 10rpx;
    }
  }
}

.toolbar {
  bottom: calc(var(--window-bottom));

  height: 100rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;

  .button {
    display: flex;
    justify-content: center;
    align-items: center;

    width: 200rpx;
    height: 72rpx;
    margin-left: 15rpx;
    font-size: 26rpx;
    border-radius: 72rpx;
    border: 1rpx solid #ccc;
    color: #444;
  }

  .secondary {
    color: #27ba9b;
    border-color: #27ba9b;
  }

  .primary {
    order: 1;
    color: #fff;
    background-color: #27ba9b;
  }
}

.popup-root {
  padding: 30rpx 30rpx 0;
  border-radius: 10rpx 10rpx 0 0;
  overflow: hidden;

  .title {
    font-size: 30rpx;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .description {
    font-size: 28rpx;
    padding: 0 20rpx;

    .tips {
      color: #444;
      margin-bottom: 12rpx;
    }

    .cell {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15rpx 0;
      color: #666;
    }

    .icon::before {
      content: '\e6cd';
      font-family: 'erabbit' !important;
      font-size: 38rpx;
      color: #999;
    }

    .icon.checked::before {
      content: '\e6cc';
      font-size: 38rpx;
      color: #27ba9b;
    }
  }

  .footer {
    display: flex;
    justify-content: space-between;
    padding: 30rpx 0 40rpx;
    font-size: 28rpx;
    color: #444;

    .button {
      flex: 1;
      height: 72rpx;
      text-align: center;
      line-height: 72rpx;
      margin: 0 20rpx;
      color: #444;
      border-radius: 72rpx;
      border: 1rpx solid #ccc;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
      border: none;
    }
  }
}
</style>
